package com.ncs.cns.business.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class DownloadUtil {
	public Bitmap getBitmap(String urlStr){
		Bitmap bm = null;
		if(urlStr.toLowerCase().startsWith("http")){
			URL url = null;
			try {
				url = new URL(urlStr);
				HttpURLConnection con = (HttpURLConnection)url.openConnection();
				con.setDoInput(true);
				con.connect();
				InputStream is = con.getInputStream();
				bm = BitmapFactory.decodeStream(is);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bm;
		}
		else{
			bm = BitmapFactory.decodeFile(urlStr);
			//bm = CompressionImageUtil.compressionImg(urlStr, null, null);
		}
		return bm;
	}
	
	public  File getSaveImagePath(){
		File path = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "CNSImg" +File.separator);
		if (!path.exists())
			path.mkdir();
		File file = new File(path, System.currentTimeMillis()+"im");
		return file;
	}
	
	public String saveImage(Bitmap bm){
		File file = getSaveImagePath();
		try {
			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(file));
			bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file.getPath();
	}
}
